import { useCallback, useEffect, useState } from "react";
import Taro from "@tarojs/taro";

import { Character } from "./type";
import { defaultSixCharacters } from "./constant";
import { getCharacter } from "./service";

// 随机获取n个角色信息
const generateRids = async (number: number) => {
  const rids: number[] = [];
  for (let i = 0; i < number; i++) {
    let rid: number;
    do {
      rid = Math.floor(Math.random() * 671) + 1;
    } while (rids.indexOf(rid) !== -1);
    rids.push(rid);
  }
  return rids;
};

export const useRandomCharacters = (number: number) => {
  const [refreshFlag, setRefreshFlag] = useState(false);
  const [characters, setCharacters] = useState<Character[]>(defaultSixCharacters);

  useEffect(() => {
    Taro.showLoading({
      title: "加载中",
      mask: true,
    });
    const rids = generateRids(number);
    getCharacter(rids)
      .then((res) => {
        setCharacters(Array.isArray(res) ? res : defaultSixCharacters);
      })
      .catch((err) => {
        setCharacters(defaultSixCharacters);
      })
      .finally(() => {
        Taro.hideLoading();
      });
  }, [number, refreshFlag]);

  const refreshCharacters = useCallback(() => setRefreshFlag((prev) => !prev), []);

  return [characters, refreshCharacters] as const;
};
